<?php

class Application_Model_ParkingMapper{

	protected $_dbTable;

	public function setDbTable($dbTable)
	{
		if (is_string($dbTable)) {
			$dbTable = new $dbTable();
		}
		if (!$dbTable instanceof Zend_Db_Table_Abstract) {
			throw new Exception('Invalid table data gateway provided');
		}
		$this->_dbTable = $dbTable;
		return $this;
	}

	public function getDbTable()
	{
		if (null === $this->_dbTable) {
			$this->setDbTable('Application_Model_DbTable_Parking');
		}
		return $this->_dbTable;
	}
	
	public function save(Application_Model_Parking $parking){
	
	
		$realestateMapper = new Application_Model_RealEstateMapper();
		$row = $realestateMapper->save($parking);
		//TODO set the object save function to return the id of the object saved
		//$where = array('model = ?' => (string)$product->getModel());
		$parking->setRealestateId($row);
	
		$data = array(
				'id_realEstate' 	=> $parking->getRealestateId(),
		);
	
		if (null === ($id = $parking->getParkingId())) {
			unset($data['id_parking']);
			return $this->getDbTable()->insert($data);
		} else {
			$this->getDbTable()->update($data, array('id_parking = ?' => $id));
			return $id;
		}
	}
	
	public function find($id, Application_Model_Parking $parking)
	{
		$result = $this->getDbTable()->find($id);
		if (0 == count($result)) {
			return;
		}
		$row = $result->current();
		$parking->setParkingId($row->id_parking);
		$parking->setRealestateId($row->id_realEstate);
	
		$realestateMapper = new Application_Model_RealEstateMapper();
		$parking = $realestateMapper->find($parking->getRealestateId(), $parking);
	
	
		return $parking;
	}
	
	public function delete($id)
	{
	
		$parking= new Application_Model_Parking();
		$realestateMapper = new Application_Model_RealEstateMapper();
		$parking = $this->find($id, new Application_Model_Parking());
	
		$result = $this->getDbTable()->find($id);
		if (0 != count($result)) {
			$this->getDbTable()->delete(array('id_parking = ?' => $id));
		}
	
		$realestateMapper->delete($parking->getRealestateId());
	
	
	}
	
	public function indexBuilder(Zend_Search_Lucene_Document $doc, Application_Model_Parking $parking)
	{
		$realestateMapper = new Application_Model_RealEstateMapper();
		$doc->addField(Zend_Search_Lucene_Field::Text('objectType', 'parking', 'utf-8'));
		$doc = $realestateMapper->indexBuilder($doc, $parking);
	
		return $doc;
	}
}